package top.canyue.eca_manager.service.impl;

import com.alibaba.fastjson2.JSON;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import top.canyue.eca_manager.bean.Conference;
import top.canyue.eca_manager.bean.Result;
import top.canyue.eca_manager.mapper.ConferenceMapper;
import top.canyue.eca_manager.service.ConferenceService;
import top.canyue.eca_manager.service.LogService;
import top.canyue.eca_manager.tool.ParamTools;

import java.sql.Timestamp;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Service
public class ConferenceServiceImpl implements ConferenceService {
    @Autowired
    ConferenceMapper conferenceMapper;

    @Autowired
    LogService logService;

    private LocalDateTime timestamToDatetime(long timestamp) {
        Instant instant = Instant.ofEpochMilli(timestamp);
        return LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
    }

    private Timestamp timestampToSqlTimestamp(long timestamp) {
        return Timestamp.valueOf(timestamToDatetime(timestamp));
    }

    @Override
    public Result findById(String id) {
        Result result = new Result();
        if (id.isEmpty()) {
            result.setStatus(500);
            result.setMsg("会议ID不得为空");
            return result;
        }
        Conference conference = conferenceMapper.findConferenceById(id);
        if (conference != null) {
            result.setStatus(200);
            result.setMsg("OK");
            result.setData(conference);
        } else {
            result.setStatus(500);
            result.setMsg("找不到会议");
        }
        return result;
    }

    @Override
    public Result getAllConferenceName() {
        Result result = new Result();
        List<Map<String, String>> names = conferenceMapper.getAllConferenceName();
        if (names.isEmpty()) {
            result.setStatus(500);
            result.setMsg("结果为空，请检查数据库数据是否完整!");
            return result;
        }
        result.setStatus(200);
        result.setMsg("OK");
        result.setData(names);
        return result;
    }

    @Override
    public Result findConferenceByName(String name, String orders, Integer offset, Integer fetchSize) {
        Result result = new Result();
        List<Conference> conferenceList;
        if (name.isEmpty()) {
            conferenceList = conferenceMapper.findAllByName(orders, offset, fetchSize);
        } else {
            if (offset < 0) {
                result.setStatus(500);
                result.setMsg("偏移量不得小于0");
                return result;
            }
            if (fetchSize < 1) {
                result.setStatus(500);
                result.setMsg("一页大小不得小于1");
                return result;
            }
            orders = orders.isEmpty() ? "createTime ASC" : orders;
            conferenceList = conferenceMapper.findConferenceByName(name, orders, offset, fetchSize);
        }
        if (conferenceList.isEmpty()) {
            result.setStatus(500);
            result.setMsg("找不到相关会议");
            return result;
        } else {
            result.setStatus(200);
            result.setMsg("OK");
            result.setData(conferenceList);
        }
        return result;
    }

    @Override
    public Result getCountByName(String name) {
        Result result = new Result();
        Integer count = conferenceMapper.getCountByName(name);
        if (count > 0) {
            result.setStatus(200);
            result.setMsg("OK");
            result.setData(count);
        } else {
            result.setStatus(500);
            result.setMsg("找不到数据");
        }
        return result;
    }

    @Override
    public Result addConference(String name, String address, long startTime, long endTime, String comm) {
        Result result = new Result();
        if (name.isEmpty()) {
            result.setStatus(500);
            result.setMsg("会议名称不得为空");
            return result;
        }
        if (startTime <= 0 || endTime <= 0) {
            result.setStatus(500);
            result.setMsg("会议起始或终止时间无效");
            return result;
        } else if (startTime > endTime) {
            result.setStatus(500);
            result.setMsg("结束会议时间不得早于起始会议时间");
            return result;
        }


        UUID uuid = UUID.randomUUID();
        String uuidStr = StringUtils.remove(uuid.toString(), '-');
        Conference conference = new Conference();
        conference.setId(uuidStr);
        conference.setName(name);
        conference.setAddress(address);
        conference.setStartTime(timestampToSqlTimestamp(startTime));
        conference.setEndTime(timestampToSqlTimestamp(endTime));
        conference.setComm(comm);
        boolean flag;
        try {
            flag = conferenceMapper.addConference(conference) == 1;
        } catch (Exception ex) {
            result.setStatus(500);
            result.setMsg("添加会议失败,可能会议部分数据与现有数据间存在冲突");
            logService.record(null, "ERROR", "addConference", ParamTools.paramsToJsonString(conference), result.getStatus());
            return result;
        }
        if (flag) {
            Map<String, String> data = new HashMap<>();
            data.put("id", uuidStr);
            result.setStatus(200);
            result.setMsg("OK");
            result.setData(JSON.toJSONString(data));
        } else {
            result.setStatus(500);
            result.setMsg("添加会议失败");
        }
        logService.record(null,
                result.getStatus() == 200 ? "INFO" : "ERROR"
                , "addConference", ParamTools.paramsToJsonString(conference), result.getStatus());
        return result;
    }

    @Override
    public Result updateConferenceInfo(String id, String name, String address, long startTime, long endTime, String comm) {
        Result result = new Result();
        if (id.isEmpty()) {
            result.setStatus(500);
            result.setMsg("会议ID不得为空");
            return result;
        }
        if (name.isEmpty()) {
            result.setStatus(500);
            result.setMsg("会名称不得为空");
            return result;
        }
        if (startTime <= 0 || endTime <= 0) {
            result.setStatus(500);
            result.setMsg("会议起始或终止时间无效");
            return result;
        } else if (startTime > endTime) {
            result.setStatus(500);
            result.setMsg("结束会议时间不得早于起始会议时间");
            return result;
        }
        Conference conference = new Conference();
        conference.setId(id);
        conference.setName(name);
        if (!address.isEmpty()) {
            conference.setAddress(address);
        }
        conference.setStartTime(timestampToSqlTimestamp(startTime));
        conference.setEndTime(timestampToSqlTimestamp(endTime));
        if (!comm.isEmpty()) {
            conference.setComm(comm);
        }

        boolean flag = conferenceMapper.updateConferenceInfo(conference) == 1;
        if (flag) {
            result.setStatus(200);
            result.setMsg("OK");
            result.setData(conference);
        } else {
            result.setStatus(500);
            result.setMsg("更新失败");
        }
        logService.record(null,
                result.getStatus() == 200 ? "INFO" : "ERROR", "updateConferenceInfo",
                ParamTools.paramsToJsonString(conference), result.getStatus());
        return result;
    }

    @Override
    public Result deleteById(String id){
        Result result = new Result();
        if(id.isEmpty()){
            result.setStatus(500);
            result.setMsg("会议ID不得为空");
            return result;
        }
        boolean flag = conferenceMapper.deleteById(id) == 1;
        if(flag){
            result.setStatus(200);
            result.setMsg("OK");
            result.setData(id);
        }else {
            result.setStatus(500);
            result.setMsg("删除失败");
        }
        logService.record(null,
                result.getStatus() == 200 ? "INFO" : "ERROR"
                , "deleteById", ParamTools.paramsToJsonString(id), result.getStatus());
        return result;
    }

    @Override
    public Result getCountByFuture(){
        Result result = new Result();
        Integer count = conferenceMapper.getCountByFuture();
        if(count >= 0){
            HashMap<String,Integer> data = new HashMap<>();
            data.put("count",count);
            result.setStatus(200);
            result.setMsg("OK");
            result.setData(data);
        }else {
            result.setStatus(500);
            result.setMsg("服务器返回数据异常");
        }
        return result;
    }
    @Override
    public Result getCountByToday(){
        Result result = new Result();
        Integer count = conferenceMapper.getCountByToday();
        if(count >= 0){
            HashMap<String,Integer> data = new HashMap<>();
            data.put("count",count);
            result.setStatus(200);
            result.setMsg("OK");
            result.setData(data);
        }else {
            result.setStatus(500);
            result.setMsg("服务器返回数据异常");
        }
        return result;
    }

    @Override
    public Result getFirstConferenceByUserId(String userId) {
        Result result = new Result();
        if (userId.isEmpty()) {
            result.setStatus(500);
            result.setMsg("用户ID不得为空");
            return result;
        }
        String conferenceId = conferenceMapper.getFirstConferenceByUserId(userId);
        if (conferenceId != null) {
            Conference conference = conferenceMapper.findConferenceById(conferenceId);
            result.setStatus(200);
            result.setMsg("OK");
            result.setData(conference);
        } else {
            result.setStatus(500);
            result.setMsg("找不到相关会议");
        }
        return result;
    }

    @Override
    public boolean updatePersistent(String id, boolean persistent) {
        Conference conference = new Conference();
        conference.setId(id);
        conference.setPersistent(persistent);
        return conferenceMapper.updateConferenceInfo(conference) == 1;
    }

    @Override
    public boolean getPersistentById(String id) {
        return conferenceMapper.getPersistentById(id) == 1;
    }

    @Override
    public Result getUserConferenceByDay(String userId, int year, int month, int day) {
        Result result = new Result();
        if (userId.isEmpty()) {
            result.setStatus(500);
            result.setMsg("用户ID不得为空");
            return result;
        }
        if (!(year > 0 && month > 0 && day > 0 && month < 12 && day < 31)) {
            result.setStatus(500);
            result.setMsg("日期值不合法");
            return result;
        }
        String date = year + "-" + month + "-" + day;
        List<Conference> conferenceList = conferenceMapper.getUserConferenceByDay(userId, date);
        result.setStatus(200);
        result.setMsg("OK");
        result.setData(conferenceList);
        return result;
    }

    @Override
    public Result getUsersHaveConferenceDaysByMonth(String userId, int year, int month) {
        Result result = new Result();
        if (userId.isEmpty()) {
            result.setStatus(500);
            result.setMsg("用户ID不得为空");
            return result;
        }
        if (!(year > 0 && month > 0 && month < 12)) {
            result.setStatus(500);
            result.setMsg("日期值不合法");
            return result;
        }
        List<Integer> days = conferenceMapper.getUsersHaveConferenceDaysByMonth(userId, year, month);
        result.setStatus(200);
        result.setMsg("OK");
        result.setData(days);
        return result;
    }
}
